<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends CI_Controller{

    
    public function __construct(){
        parent::__construct();
        $this->load->model('user','',true);
    }

	public function index(){
        if ($this->session->userdata('isLoggedIn')){
            redirect('site');
        }else {
        $this->load->view('header');
        $this->load->view('login');
        $this->load->view('footer');
    }
	}

    public function login(){
        $valid = false;
		$users = $this->user->get_user();
		$username = $this->input->post('username');// mengambil user nama dari text field yang ada di form login
        $password = $this->input->post('password');// mengambil password dari text field yang ada di form login
        
        foreach ($users->result() as $row) {
            if ($username == $row->username && md5($password) == $row->password) {
                $valid = true;

                //setting session terhadap data user
                $newdata = array(
                    'username' => $username,
                    'password' => $password,
                    'isLoggedIn'=> true
                );
		
                $this->session->set_userdata($newdata);
                
                break;
            }
            }//end foreach
        //apabila login telah sesuai dengan username dan password maka user akan masuk halaman utama
        if ($valid) {
           redirect('site');
        }
        //apabila login tidak sesuai dengan username dan password maka user akan masuk halaman login
        else {
            redirect('auth/false');
        }
    }

	public function false(){
        $data['false']="Maaf Username/password salah";
        $this->load->view('header');
        $this->load->view('login',$data);
        $this->load->view('footer');
    }
    
    public function logout()
    {    
        $this->session->sess_destroy();
        $_SESSION = array();
        if (ini_get("session.use_cookies")) {
    		$params = session_get_cookie_params();
    		setcookie(session_name(), '', time() - 42000,
        	$params["path"], $params["domain"],
        	$params["secure"], $params["httponly"]
    		);
        }session_destroy();  	
        redirect('site');
    }

}